const dotenv = require('dotenv');
const result = dotenv.config();
if (result.error) {
    throw result.error;
}
const retry = require('bluebird-retry');
const retryPromise = require('bluebird');
const config = require('./config');
const MetamonApi = require('./metamon_api');
const Web3 = require('web3');

let wait = ms => new Promise(resolve => setTimeout(resolve, ms));
let metamonApi = new MetamonApi(config.address, config.chain, config.privateKey);

async function run() {
    console.log("Raca-Metamon自动喝药脚本启动，当前账号: " + config.address);
    if (config.accessToken) {
        metamonApi.setAccessToken(config.accessToken);
    } else {
        /// 程序登录，设置accessToken
        let accessToken = await metamonApi.login();
        metamonApi.setAccessToken(accessToken);
    }


    let timeOut = config.loopSeconds * 1000;
    let count = 1;
    (function iterator() {
        runThis(count).then((res) => {
            if (res) {
                console.log("元兽喝药完毕");
                return;
            }
            setTimeout(() => {
                count++;
                iterator();
            }, timeOut);
        }).catch((err) => {
            console.log(`error: ${err.message}`);
            console.log(err);
            setTimeout(() => {
                count++;
                iterator();
            }, timeOut);
        })
    })();
}

async function runThis(count) {
    console.log("============================程序开始第" + count + "次扫描==============================");
    try {
        let metamons = await metamonApi.getMetamonList();
        /// 查询背包获取药水数量
        let potions = await getNft(2, metamonApi);
        console.log("当前药水数量" + potions.bpNum);
        let isCompleted = true;
        for (let i = 0; i < metamons.length; i++) {
            let m = metamons[i];
            for (let j=0; j<2; j++ ) {
                if (m.level >= 60) {
                    console.log("元兽#"+m.id+"已满60级无需喝药");
                    break;
                }
                let nftId = m.id;
                let result = await metamonApi.addExp(nftId);
                if (result.result == 1) {
                    console.log("元兽#"+m.id+"增加经验："+result.data);
                    isUpper = 1;
                } else if (result.code == 'EXP_UPPER_LIMIT_ERROR') {
                    console.log("元兽#"+m.id+"今日已喝药");
                    break;
                } else {
                    console.log("元兽#"+m.id+"增加经验失败："+result.message);
                    isCompleted = false;
                }
            }
        }
        let status = await metamonApi.batchUpgradeStatus();
        if (status.data.status) {
            
            let needPay = await metamonApi.batchUpgradePay();
            if (needPay.result == 1) {
                console.log("检测到有元兽可进行升级，启动批量升级");
                let p = await metamonApi.batchUpgradeOperate();
                if (p.result == 1) {
                    console.log("批量升级"+p.data.upgradeNum+"只元兽！");
                } else {
                    console.log("批量升级失败："+p.message);
                }
            } else {
                
            }
            
        }
        return isCompleted;
    } catch (e) {
        console.log(e);
        return false;
    }

}



/// 获取特定NFT
async function getNft(bpType, metamonApi) {
    let nfts = await metamonApi.checkBag();
    let nft;
    for (let i = 0; i < nfts.length; i++) {
        let item = nfts[i];
        if (item.bpType == bpType) {
            nft = item;
            break;
        }
    }
    return nft;
}


run();